<div id="vue-platform"></div>
    <script>
        Dcat.ready(function () {
            const { ref, reactive, watch, onMounted } = Vue
            window.appInit("#vue-platform",{
                template:`
<div>
<n-space class="w-full">
    <n-form class="w-full" inline label-placement="left"
            label-width="auto" :model="goodSearch">
        <n-space class="mr-1" style="margin-top: 5px">
            <n-button circle type="primary" size="small" @click="onRefresh"> <i class="fa fa-refresh"></i> </n-button>
            <n-button type="info" size="small" @click="addPlatformGood">新增平台商品</n-button>
            <n-button type="error" size="small" @click="mutilDelete">取消平台商品</n-button>
        </n-space>
        <n-form-item label="商品分类">
            <n-cascader
                v-model:value="goodSearch.category_id"
                expand-trigger="hover"
                :options="categoryOptions"
                check-strategy="all"
                filterable
                show-path
                value-field="id"
                label-field="name"
                clearable
                placeholder="请选择商品分类"
            ></n-cascader>
            </n-form-item>
        <n-form-item label="商品名称">
            <n-input v-model:value="goodSearch.name" type="text" placeholder="请输入商品名称" clearable></n-input>
        </n-form-item>
    </n-form>
</n-space>
<n-data-table
    :loading="goodLoading"
    :pagination="goodPagination"
    :columns="goodColumns"
    :data="goodsList"
    :row-key="goodRowKey"
    @update:checked-row-keys="handleGoodChecked"
></n-data-table>
<n-drawer v-model:show="showDrawer" width="70%">
    <n-drawer-content title="平台商品" closable>
        <n-space class="w-full">
            <n-form class="w-full" inline label-placement="left"
                    label-width="auto" :model="searchGoods">
                <n-form-item label="商品分类">
                    <n-cascader
                        v-model:value="searchGoods.category_id"
                        expand-trigger="hover"
                        :options="categoryOptions"
                        check-strategy="all"
                        filterable
                        show-path
                        value-field="id"
                        label-field="name"
                        clearable
                        placeholder="请选择商品分类"
                    ></n-cascader>
                   </n-form-item>
                <n-form-item label="商品名称">
                    <n-input v-model:value="searchGoods.name" type="text" placeholder="请输入商品名称" clearable></n-input>
                </n-form-item>
            </n-form>
        </n-space>
        <n-button type="primary" size="small" style="margin-bottom: 4px" @click="mutilSelect">批量选择加入</n-button>
        <n-data-table
            remote
            flex-height
            :loading="loading"
            :columns="platformColumns"
            :data="platformGoods"
            :pagination="paginationReactive"
            :row-key="rowKey"
            @update:checked-row-keys="handleChecked"
            style="height: calc(100vh - 220px)"
        ></n-data-table>
    </n-drawer-content>
</n-drawer>
<n-drawer v-model:show="goodDrawer" width="70%">
    <n-drawer-content title="编辑平台商品" closable>
        <n-form class="w-full" inline label-placement="left"
                label-width="auto" :model="goodForm">
            <div style="width: 100%">
                <n-descriptions  label-placement="left" bordered :column="3">
                    <n-descriptions-item label="商品名称">@{{goodForm.goods.name||''}}</n-descriptions-item>
                    <n-descriptions-item label="商品分类">@{{goodForm.goods.category.name||''}}</n-descriptions-item>
                    <n-descriptions-item label="商品图片">
                        <n-image width="30" height="30" :src="goodForm.goods.image"></n-image>
                    </n-descriptions-item>
                    <n-descriptions-item label="商品售价">@{{goodForm.goods.price||0.00}}元</n-descriptions-item>
                    <n-descriptions-item label="商品库存">@{{goodForm.goods.stock||0}}</n-descriptions-item>
                    <n-descriptions-item label="商品成本价">@{{goodForm.goods.cost_price||0.00}}元</n-descriptions-item>
                    <n-descriptions-item label="规格类型">@{{goodTypes[goodForm.goods.type]}}</n-descriptions-item>
                    <n-descriptions-item label="上架状态" >
                        <n-switch
                            v-model:value="goodForm.state"
                            :checked-value="0"
                            :unchecked-value="1"
                        >
                            <template #checked>
                                已上架
                            </template>
                            <template #unchecked>
                                已下架
                            </template>
                        </n-switch>
                    </n-descriptions-item>
                    <n-descriptions-item label="售价范围"> <span v-if="goodForm.goods.type===0"> @{{goodForm.start_price}}元 ~ @{{goodForm.end_price}}元</span> <span v-else>-</span> </n-descriptions-item>
                    <n-descriptions-item label="商品SKU">
                        {{--                            goodForm.goods.type--}}
                            <n-input-number
                        v-if="goodForm.goods.type===0"
                        v-model:value="goodForm.price"
                        placeholder="最小值"
                        :step="1"
                        :precision="2"
                        :min="goodForm.start_price"
                        :max="goodForm.end_price"
                        style="width: 180px"
                    >
                        <template #prefix>
                            <i class="fa fa-rmb"></i>
                        </template>
                    </n-input-number>
                        <n-table class="table" v-else >
                            <n-thead>
                                <n-tr>
                                    <n-th>规格</n-th>
                                    <n-th>库存</n-th>
                                    <n-th>售价范围</n-th>
                                    <n-th>价格</n-th>
                                </n-tr>
                            </n-thead>
                            <n-tbody>
                                <template v-for="(sku) in goodForm.sku_list">
                                    <n-tr>
                                        <n-th>@{{getSkuAttrs(goodForm.sku_keys,sku)}}</n-th>
                                        <n-td>@{{sku.stock}}</n-td>
                                        <n-th>@{{sku.start_price}}元 ~ @{{sku.end_price}}元</n-th>
                                        <n-td>
                                            <n-input-number
                                                v-model:value="goodForm.sku_prices[sku.key]"
                                                placeholder="最小值"
                                                :step="1"
                                                :precision="2"
                                                :min="sku.start_price"
                                                :max="sku.end_price"
                                                style="width: 180px"
                                            >
                                                <template #prefix>
                                                    <i class="fa fa-rmb"></i>
                                                </template>
                                            </n-input-number>
                                        </n-td>
                                    </n-tr>
                                </template>
                            </n-tbody>
                        </n-table>
                    </n-descriptions-item>
                </n-descriptions>
            </div>
        </n-form>
        <template #footer>
            <n-button type="info" @click="onSaveGoodForm">提交</n-button>
        </template>
    </n-drawer-content>
</n-drawer>
</div>
`,
                setup() {
                    const loading = ref(false)
                    const goodLoading = ref(false)
                    const goodSearch = ref({
                        category_id: null,
                        name: ""
                    })
                    const categoryOptions = @json($category);
                    const searchGoods = ref({
                        category_id: null,
                        name: ""
                    })
                    const showDrawer = ref(false)
                    const goodDrawer = ref(false)
                    const goodForm = ref({
                        goods:{
                            category_id: null,
                            name:"",
                            start_price: 0.00,
                            end_price: 0.00,
                        },
                        start_price: 0.00,
                        end_price: 0.00,
                        price:0.00,
                        type:0,
                        sku_prices: null
                    })
                    const goodTypes = ['单规格','多规格'];
                    const statusList = ['上架','下架'];
                    const rowKeys = ref([])
                    const goodKeys = ref([])
                    const platformGoods = ref([])
                    const goodsList = ref([])
                    const platformColumns = ref([
                        {
                            type: 'selection',
                            // disabled (row: RowData) {
                            //     return row.name === 'Edward King 3'
                            // }
                        },
                        { title: '商品ID',key: 'id' },
                        { title: '商品分类', key: 'category.name' },
                        { title: '商品名称', key: 'name' },
                        { title: '商品图片', key: 'image',
                            render: (row)=>{
                                return Vue.h(Vue.resolveComponent('n-image'),{
                                    width: 45, height:45, src: row.image
                                })
                            }
                        },
                        { title: '商品成本价(￥)',  key: 'cost_price' },
                        { title: '商品售价(￥)',  key: 'price' },
                        { title: '商品库存', key: 'stock' },
                        { title: '规格类型', key: 'type', render:(row)=>{  return goodTypes[row.type] } },
                        { title: '操作', key: 'action', fixed: 'right',
                            render:(row)=>{
                                return Vue.h(Vue.resolveComponent('n-button'),{
                                    type:"primary",size:"small",
                                    onClick: ()=>{
                                        addGoodToShop(row.id)
                                    }
                                },"选择加入")
                            }
                        },
                    ])

                    const dialogConfirm = ($callback, options = {})=>{
                        if(options.type==='error'||options.type===undefined){
                            const d = window.$dialog.error({
                                title: options.title || '取消平台商品',
                                content: options.content || '是否确认取消平台商品',
                                positiveText: '确认',
                                negativeText: '关闭',
                                onPositiveClick: () => {
                                    return new Promise((resolve) => $callback(resolve, d))
                                }
                            })
                        }else{
                            const d = window.$dialog.success({
                                title: options.title || '取消平台商品',
                                content: options.content || '是否确认取消平台商品',
                                positiveText: '确认',
                                negativeText: '关闭',
                                onPositiveClick: () => {
                                    return new Promise((resolve) => $callback(resolve, d))
                                }
                            })
                        }
                    }

                    const goodColumns = ref([
                        { type: 'selection'},
                        { title: '关联ID', key: 'id', className: '' },
                        { title: '商品ID',key: 'goods.id' },
                        { title: '商品分类', key: 'goods.category.name' },
                        { title: '商品名称', key: 'goods.name' },
                        { title: '商品图片', key: 'goods.image',
                            render: (row)=>{
                                return Vue.h(Vue.resolveComponent('n-image'),{
                                    width: 45, height:45, src: row.goods.image
                                })
                            }
                        },
                        { title: '商品成本价(￥)',  key: 'goods.cost_price' },
                        { title: '商品售价(￥)',  key: 'price' },
                        { title: '商品库存', key: 'goods.stock' },
                        { title: '规格类型', key: 'goods.type', render:(row)=>{  return goodTypes[row.goods.type] } },
                        { title: '状态', key: 'state', render:(row)=>{
                                return Vue.h(Vue.resolveComponent('n-switch'),{
                                    checkedValue: 0,
                                    uncheckedValue:1,
                                    value: row.state,
                                    'onUpdate:value':(value)=>{
                                        value? row.state = 1: row.state = 0
                                        $.ajax({
                                            url:"/shop/updateGoodsState",
                                            method:"POST",
                                            data:{ id:row.id, state:value },
                                            success(res){
                                                if(res.status){
                                                    Dcat.success(res.data.message);
                                                }else{
                                                    Dcat.error(res.data.message);
                                                }
                                            },
                                            error(error){
                                                reject(error)
                                            }
                                        })
                                    }
                                },{
                                    checked:()=>"已上架",
                                    unchecked:()=>"已下架",
                                })
                            }
                        },
                        { title: '操作', key: 'action', fixed: 'right',
                            render:(row)=>{
                                return Vue.h(Vue.resolveComponent('n-button-group'),{ size: "small" },[
                                    Vue.h(Vue.resolveComponent('n-button'),{
                                        type:"info",size:"small",
                                        onClick: ()=>{
                                            goodForm.value = row;
                                            console.log(goodForm.value)
                                            setTimeout(()=>{
                                                goodDrawer.value = true;
                                            },500)
                                        }
                                    },"编辑"),
                                    Vue.h(Vue.resolveComponent('n-button'),{
                                        type:"error",size:"small",
                                        onClick: ()=>{
                                            dialogConfirm(function (resolve, d){
                                                d.loading = true;
                                                deleteGood(row.id).then(()=>{
                                                    d.loading = false;
                                                    resolve(true);
                                                })
                                            },{
                                                content: "是否取消平台商品【"+row.goods.name+"】?"
                                            })
                                        }
                                    },"取消")
                                ])
                            }
                        },
                    ])

                    const getPagination = ()=>{
                        return {
                            page: 1,
                            pageCount: 1,
                            pageSize: 8,
                            prefix ({ itemCount }) {
                                return `总数: ${itemCount}.`
                            },
                            showSizePicker: true,
                            pageSizes: [8, 16, 32]
                        }
                    }

                    const paginationReactive = reactive({
                        // page: 1,
                        // pageCount: 1,
                        // pageSize: 8,
                        // prefix ({ itemCount }) {
                        //     return `总数: ${itemCount}.`
                        // },
                        // showSizePicker: true,
                        // pageSizes: [8, 16, 32],
                        ...getPagination(),
                        onChange: (page) => {
                            paginationReactive.page = page
                            getPlatformGoods()
                        },
                        onUpdatePageSize: (pageSize) => {
                            paginationReactive.pageSize = pageSize
                            paginationReactive.page = 1
                            getPlatformGoods()
                        }
                    })

                    const goodPagination = reactive({
                        ...getPagination(),
                        onChange: (page) => {
                            goodPagination.page = page
                            getGoodsList()
                        },
                        onUpdatePageSize: (pageSize) => {
                            goodPagination.pageSize = pageSize
                            goodPagination.page = 1
                            getGoodsList()
                        }
                    })
                    const addPlatformGood = ()=>{
                        showDrawer.value = true
                    }
                    const getPlatformGoods = ()=>{
                        loading.value = true;
                        let { name, category_id } = searchGoods.value
                        let params = "page="+paginationReactive.page;
                        params+= "&pageSize="+paginationReactive.pageSize;
                        params+= "&category_id=" + (category_id?category_id:"");
                        params+= "&name="+name;
                        $.ajax({
                            url:"/shop/getPlatformGoods?"+params,
                            method:"GET",
                            success(res){
                                const data = res.data;
                                paginationReactive.pageCount = data.pageCount
                                paginationReactive.itemCount = data.total
                                if(res.status){
                                    platformGoods.value = data.items;
                                }
                                loading.value = false;
                            }
                        })
                    }
                    const getGoodsList = ()=> {
                        goodLoading.value = true;
                        let { name, category_id } = goodSearch.value
                        let params = "page="+goodPagination.page;
                        params+= "&pageSize="+goodPagination.pageSize;
                        params+= "&category_id=" + (category_id?category_id:"");
                        params+= "&name="+name;
                        $.ajax({
                            url:"/shop/getGoodsList?"+params,
                            method:"GET",
                            success(res){
                                const data = res.data;
                                goodPagination.pageCount = data.pageCount
                                goodPagination.itemCount = data.total
                                if(res.status){
                                    goodsList.value = data.items;
                                }
                                goodLoading.value = false;
                            }
                        })
                    }

                    onMounted(()=>{
                        getPlatformGoods()
                        getGoodsList()
                    })
                    watch(()=>searchGoods,()=>{
                        getPlatformGoods()
                    },{ deep:true })
                    watch(()=>goodSearch,()=>{
                        getGoodsList()
                    },{ deep:true })

                    const addGoodToShop = (ids)=>{
                        return new Promise((resolve, reject)=>{
                            $.ajax({
                                url:"/shop/addGoodToShop",
                                method:"POST",
                                data:{ ids },
                                success(res){
                                    if(res.status){
                                        Dcat.success(res.data.message);
                                        getPlatformGoods()
                                        getGoodsList()
                                    }else{
                                        Dcat.error(res.data.message);
                                    }
                                    resolve(true)
                                },
                                error(error){
                                    reject(error)
                                }
                            })
                        })
                    }

                    const deleteGood = (ids)=>{
                        return new Promise((resolve, reject)=>{
                            $.ajax({
                                url:"/shop/deleteGood",
                                method:"POST",
                                data:{ ids },
                                success(res){
                                    if(res.status){
                                        Dcat.success(res.data.message);
                                        getGoodsList()
                                        getPlatformGoods()
                                    }else{
                                        Dcat.error(res.data.message);
                                    }
                                    resolve(true)
                                },
                                error(error){
                                    reject(error)
                                }
                            })
                        })
                    }

                    const handleChecked = (keys)=>{
                        rowKeys.value = keys
                    }
                    const handleGoodChecked = (keys)=>{
                        goodKeys.value = keys;
                    }
                    const mutilSelect = ()=>{
                        if(!rowKeys.value.length){
                            Dcat.error("请先选择商品!");
                            return false;
                        }
                        dialogConfirm(function (resolve, d){
                            d.loading = true;
                            addGoodToShop(rowKeys.value.join(",")).then(()=>{
                                d.loading = false;
                                resolve(true);
                            })
                        },{
                            title:"添加平台商品",
                            content: "是否批量添加平台商品",
                            type:"info"
                        })
                    }
                    const mutilDelete = ()=>{
                        if(!goodKeys.value.length){
                            Dcat.error("请先选择商品!");
                            return false;
                        }
                        dialogConfirm(function (resolve, d){
                            d.loading = true;
                            deleteGood(goodKeys.value.join(',')).then(()=>{
                                d.loading = false;
                                resolve(true);
                            })
                        })
                    }
                    const getSkuAttrs = (keys, sku)=>{
                        const attrs = [];
                        keys.forEach(item=>{
                            attrs.push(item+":"+sku[item])
                        })
                        return attrs.join(" - ");
                    }
                    const onSaveGoodForm = ()=>{
                        const { id, type, price, sku_prices, state } = goodForm.value
                        $.ajax({
                            url:"/shop/updateGoodsSkuPrices",
                            method:"POST",
                            data:{ id, type, price, sku_prices, state },
                            success(res){
                                if(res.status){
                                    Dcat.success(res.data.message);
                                    getGoodsList()
                                }else{
                                    Dcat.error(res.data.message);
                                }
                            },
                            error(error){
                                reject(error)
                            }
                        })
                    }
                    return {
                        showDrawer,
                        platformGoods,
                        platformColumns,
                        addPlatformGood,
                        paginationReactive,
                        zhCN: naive.zhCN,
                        dateZhCN: naive.dateZhCN,
                        loading,
                        searchGoods,
                        categoryOptions,
                        handleChecked,
                        rowKey: (row) => row.id,
                        goodRowKey: (row) => row.id,
                        mutilSelect,
                        goodLoading,
                        goodPagination,
                        goodSearch,
                        goodColumns,
                        goodsList,
                        goodDrawer,
                        onRefresh: getGoodsList,
                        mutilDelete,
                        handleGoodChecked,
                        goodForm,
                        goodTypes,
                        getSkuAttrs,
                        onSaveGoodForm
                    }
                }
            })
        })
    </script>
